package com.candy.login;

import com.candy.jdbcutil.JDBCUtils;
import com.candy.pojo.Student;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

//@WebServlet(name = "Servlet")
public class LoginServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        //在Servletcontext域中存一个数据count
        int count =0;
        this.getServletContext().setAttribute("count",count);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //通过一个头Context-Type 告知客户端实验何种码表
        //resp.setHeader("Context-Type","text/html;charset=UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //获得用户名和密码
        String username = req.getParameter("username");
        System.out.println(username);
        String password = req.getParameter("password");
        //从数据库中验证改用户名和密码是否正确
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        String sql = "select * from tb_student where tid=? and name=?";
        Student stu=null;
        try {
            stu = qr.query(sql,new BeanHandler<Student>(Student.class),username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //根据返回的结果给用户不同显示信息
        if(stu!=null){
            //从servletcontext中取出count进行++运算
            ServletContext context = this.getServletContext();
            Integer count = (Integer) context.getAttribute("count");
            count++;
            //用户登录成功
            resp.getWriter().write(stu.toString()+"you are success loginperson:"+count);
            context.setAttribute("count",count);
        }else {
            //用户登录失败
            resp.getWriter().write("登录失败");
        }
    }
}
